<?php

/**
 * 澳免SDK
 * @author chenyun
 */

namespace App\Service\VendorClient\Shopaomian;
use App\Model\PssModel\ServiceConfig;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;

class ShopaomianApiClient
{
    private $account  = 'shopaomian';
    protected $config;
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', 16);
        
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        //运费
        $deliver_money  = bcmul($orderInfo['deliver_money'], '100');
        //商品下单组
        $goods = [];
        $productAmt = $TaxAmt = 0 ;
        foreach ($params['orderGoods'] as $key => $item )
        {
            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity ;
            
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,3);
            $singleGoodsPrice   = ceil(bcmul((string)$singleGoodsPrice,(string)'100',1));
            $totalGoods         = bcmul((string)$singleGoodsPrice,(string)$buyAcount);
            
            //商品组
            $goods[] = [
                'goods_no'  => $item['supplier_skucode'],
                'number'    => $buyAcount,
                'total'     => $totalGoods,
            ];

            $productAmt = bcadd((string)$productAmt,(string)$totalGoods,2);
        }
        
        //实际下单金额
        $real_total_money   = bcmul($orderInfo['real_total_money'], '100');
        
        //订单总金额 = 含税商品总金额 + 运费 - 优惠金额
        $ActualPaidAmt      = bcadd((string)$productAmt,(string)$TaxAmt);
        $ActualPaidAmt      = bcadd((string)$deliver_money,(string)$ActualPaidAmt);
        
        //优惠金额
        $discount_money     = bcsub((string)$ActualPaidAmt,$real_total_money);
        
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        
        //支付时间
        $payTime        = empty($order['payTime']) ? $orderInfo['pay_time'] :$order['payTime'];
        //支付时间
        $pay_time       = $payTime ? $payTime : time();
        $pay_time       = date('Y-m-d H:i:s',$pay_time);
        
        
        //支付流水号
        $pay_sn         = $order['paySerial']??$orderInfo['pay_sn'];
        $deduction      = 0.00;
        
        //获取上游供应商支付方式路由
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $PayCompanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        $pay_value      = ServiceConfig::instance()->getConfigByEventsValue($this->account, ServiceConfig::TYPE_PAY, $PayCompanyCode);
        if (empty($pay_value)) {
            return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$PayCompanyCode}】未映射，请联系管理员处理");
        } 
        //电商平台信息
        $enterpriseNum = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ? $order['enterpriseName'] : $enterpriseName;
        
        //创建订单数据
        $orderData = [
            'order_no'     => $orderInfo['supplier_dsn'],
            'create_time'  => date("Y-m-d H:i:s",$orderInfo['cd']),
            'pay_time'     => $pay_time,
            'total_price'  => $real_total_money,
            'total_tax'    => 0,
            'total_fright' => $deliver_money,
            'f_discount'   => $discount_money,
            'customs'      => [
                'idcard'         => $orderInfo['buyer_idcard'],
                'idcard_name'    => $orderInfo['buyer_realname'],
                'pay_no'         => $pay_sn,
                'order_decla_no' => $orderInfo['supplier_dsn'],
                'plaform_code'   => $enterpriseNum,
                'pay_id'         => $pay_value,
            ],
            'address'      => [
                'consignee'      => $orderInfo['receive_name'],
                'consignee_phone'=> $orderInfo['recveive_phone'],
                'province'       => $orderInfo['province'],
                'city'           => $orderInfo['city'],
                'area'           => $orderInfo['district'],
                'address'        => $orderInfo['receive_address'],
            ],
            'goods'         => $goods,
        ];
        $pushData=[
            'warehouse_no' => $this->config["warehouse_no"],
            'customer_no'  => $this->config["customer_no"],
            'charset'      => "UTF-8",
            'nonce_str'    => $this->randstrpay(),
            'method'       => "order_add",
            'sign_type'    => "MD5",
            'query_params' => json_encode($orderData, JSON_UNESCAPED_UNICODE),
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $pushData
        ];
       $res= $this->execute($requestParam);
       if( $res['code'] == Normal::SUC ) {
           return Normal::returnCode(Normal::SUC,"订单推送成功",[
               'thirdpart_order_sn' => $res["data"]["data"][0]["orderNo"]
           ]);
       }
        return $res;
    }
   
    /**
     * 获取取消订单
     */
    public function cancelOrder( $params = [] ) 
    {
        if( empty($params['supplierOrder'])) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder ");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $data = [
            'order_no' => $orderInfo['supplier_dsn'],
            'message'  => $order['exceptReason'] ? $order['exceptReason'] : "人工运营处理售后退款",
        ];
        
        $pushData=[
            'warehouse_no' => $this->config["warehouse_no"],
            'customer_no'  => $this->config["customer_no"],
            'charset'      => "UTF-8",
            'nonce_str'    => $this->randstrpay(),
            'method'       => "platform_order_cancel",
            'sign_type'    => "MD5",
            'query_params' => json_encode($data, JSON_UNESCAPED_UNICODE),
        ];
        $requestParam = [
            'method'    => 'cancelOrder',
            'data'      => $pushData
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 加签
     * @param array $param
     */
    protected function getSign( array $param = [] )
    {
        //第一步：将参数（除去sign外）以字典序升序排序
        ksort($param);
        //第二步：拼接参数和参数值（key1=value1&key2=value2........）得到原始字符串 str。
        $string="";
        foreach ($param as $k=>$v){
            $string.=$k."=".$v."&";
        }
        $string=substr($string,0, -1);
        //第三步：将待签名字符串做MD5加密后放入请求参数 sign传入服务器
        $string = md5($string.$this->config["customer_no"]);
        return $string;
    }
    
    /**
     * 随机32位字符串
     */
    function randstrpay($length=32) { 
        $rand=''; 
        $randstr= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 
        $max = strlen($randstr)-1; 
        mt_srand((double)microtime()*1000000); 
        for($i=0;$i<$length;$i++) {
            $rand.=$randstr[mt_rand(0,$max)]; 
        } 
        return $rand; 
    }
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    { 
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        $method = $param['method'];
        $param["data"]["sign"] = $this->getSign($param['data']);
        $url = $this->config['baseurl'];
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => "post",
                'format'    => 'x-www-form-urlencoded',
                'header'    => [],
        
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res,true);
        if( isset($resHttp['errorCode']) && $resHttp['errorCode'] == 0 ) {
            return Normal::returnCode(Normal::SUC,$resHttp['errorMsg'],$resHttp);
        }
        $message = isset($resHttp['errorMsg']) ? $resHttp['errorMsg'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}